<?php
namespace Api\Controller;
vendor('Firebase.JWT.JWT');

class TeacherController extends BaseController {
    //用户名密码登录
    public function login() {
        if (!$_POST) {
            fail("需要post请求");
        }
        $data = get_trim_data(get_auto_data($_REQUEST));
        $username = $data['username'];
        $password = $data['password'];
        if (!$username) {
            fail_name('参数错误', 'username');
        }
        if (!$password) {
            fail_name('参数错误', 'password');
        }
        //查找老师
        $teacher = M('teacher')->field('uid,password,salt,phone,nick_name,gender,age,head_img,income,cid')->where(array(
            'username' => $username
        ))->find();
        if (!$teacher) {
            fail('用户不存在');
        }
        //判断密码是否正确
        if (jiami($password . $teacher['salt']) != $teacher['password']) {
            fail('密码错误');
        }
        if (!$teacher['cid']) {
            fail('未获取到您的负责科目，请联系管理员设置');
        }
        //解析出这个老师所教的课程
        $cate_res = M()->query("select c.cname as child_name,c1.cname as parent_name 
                  from t_category as c,t_category as c1
                  WHERE c.cid= '{$teacher['cid']}' AND c.cparent_id=c1.cid");
        if (!$cate_res || !$cate_res[0]) {
            fail('您的负责科目异常，请联系管理员设置');
        }
        $teacher['parent_name'] = str_replace('科目', '', $cate_res[0]['parent_name']);
        $teacher['child_name'] = $cate_res[0]['child_name'];
        //生成token并返回
        $token ['uid'] = $teacher['uid'];
        $token ['time'] = time();
        $jwt = \Firebase\JWT\JWT::encode($token, C('COOKIE'));
        $teacher['token'] = $jwt;
        unset($teacher['password']);
        unset($teacher['salt']);
        succeed(get_auto_data($teacher));
    }

    public function getUserInfo() {
        $uid = isLogin();
        if (!$uid) {
            fail_login('请登录后操作');
        }
        //查找老师
        $teacher = M('teacher')->field('uid,phone,nick_name,gender,age,head_img,income,cid')->where(array(
            'uid' => $uid
        ))->find();
        //解析出这个老师所教的课程
        $cate_res = M()->query("select c.cname as child_name,c1.cname as parent_name 
                  from t_category as c,t_category as c1
                  WHERE c.cid= '{$teacher['cid']}' AND c.cparent_id=c1.cid");
        if (!$cate_res || !$cate_res[0]) {
            fail('您的负责科目异常，请联系管理员设置');
        }
        $teacher['parent_name'] = str_replace('科目', '', $cate_res[0]['parent_name']);
        $teacher['child_name'] = $cate_res[0]['child_name'];
        unset($teacher['password']);
        unset($teacher['salt']);
        succeed(get_auto_data($teacher));
    }

    /**
     * 获取教师的订单回复总结
     */
    public function getConclusion() {
        $uid = isLogin();
        if (!$uid) {
            fail_login('请登录后操作');
        }
        //获取教师总共待处理多少单，已处理多少单
        $res = M()->query("SELECT count(h.hid) as total,t.income,
                    count(CASE h.process_state WHEN 1 THEN 1 END) AS process_count_wait,
                    count(CASE h.process_state WHEN 2 THEN 2 END ) AS process_count_done
                    FROM t_qdeal_history as h,t_teacher as t
                    WHERE h.uid='{$uid}'
                    AND t.uid= h.uid;");
        if ($res) {
            succeed(get_auto_data($res[0]));
        } else {
            succeed(get_auto_data(array(
                "total"              => 0,
                "process_count_wait" => 0,
                "process_count_done" => 0,
                "income"             => 0.00
            )));
        }
    }

    public function getTeachers() {
        $uid = isLogin();
        if (!$uid) {
            fail_login('请登录后操作');
        }
        $data = get_auto_data($_REQUEST);
        //1.必填参数判断
        $pageNo = $data['pageNo'];
        $pageSize = $data['pageSize'];
        if (!is_numeric($pageNo) || $pageNo < 0) {
            fail_name('pageNo');
        }
        if (!is_numeric($pageSize) || $pageSize < 0) {
            fail_name('pageSize');
        }
        $queryIndexStart = $pageNo * $pageSize;
        $teacher_list = M()->query("select t.uid,t.username,t.gender,t.age,t.nick_name,t.head_img,
                      t.country,t.province,t.city,t.income,t.cid,t.create_time,c.cname,(select c1.cname from t_category c1 where c.cparent_id=c1.cid) as parent_name,
                      count(h.hid) as processedCount
                      from t_teacher as t
                      LEFT JOIN  t_category as c ON  t.cid=c.cid
                      LEFT JOIN  t_qdeal_history as h ON  h.uid=t.uid AND h.process_state=2
                      GROUP BY t.uid
                      order by t.create_time desc
                      limit {$queryIndexStart},{$pageSize};");
        succeed(get_auto_data($teacher_list));
    }

    /**
     */
    public function createNewOrUpdate() {
        $uid = isLogin();
        if (!$uid) {
            fail_login('请登录后操作');
        }
        if (!$_POST) {
            fail("需要post请求");
        }
        $data = get_auto_data($_REQUEST);
        $cid = $data['cid'];
        if (!$cid) {
            fail_name('cid');
        }
        $nick_name = $data['nick_name'];
        if (!$nick_name) {
            fail_name('nick_name');
        }
        $head_img = $data['head_img'];
        if (!$head_img) {
            fail_name('head_img');
        }
        $gender = $data['gender'];
        if (!$gender) {
            fail_name('gender');
        }
        $urltype = $data['urltype']; //1新增  2修改
        if (!$urltype) {
            fail_name('urltype');
        }
        $current_time = time();
        if ($urltype == 1) {
            //新增
            $username = $data['username'];
            if (!$username) {
                fail_name('username');
            }
            $pwd = $data['pwd'];
            if (!$pwd) {
                fail_name('pwd');
            }
            //查看用户是否存在
            $count = M('teacher')->where(array(
                'username' => $username,
            ))->count();
            if ($count > 0) {
                fail('用户已存在');
            }
            $salt = make_salt();
            $res = M('teacher')->add(array(
                'uid'         => createIdStr(),
                'username'    => $username,
                'password'    => jiami($pwd . $salt),
                'salt'        => $salt,
                'cid'         => $cid,
                'nick_name'   => $nick_name,
                'head_img'    => $head_img,
                'gender'      => $gender,
                'create_time' => $current_time,
                'update_time' => $current_time,
            ));
        } else {
            $teacher_uid = $data['teacher_uid'];
            if (!$teacher_uid) {
                fail_name('teacher_uid');
            }
            //修改
            $res = M('teacher')->where(array(
                'uid' => $teacher_uid,
            ))->save(array(
                'cid'         => $cid,
                'nick_name'   => $nick_name,
                'head_img'    => $head_img,
                'gender'      => $gender,
                'update_time' => $current_time,
            ));
        }
        if ($res) {
            succeed(null, '创建成功');
        } else {
            fail('创建教师失败，请重试');
        }
    }

    //修改密码
    public function modifyPwd() {
        $uid = isLogin();
        if (!$uid) {
            fail_login('请登录后操作');
        }
        $data = get_trim_data(get_auto_data($_REQUEST));
        $pwd_origin = $data['pwd_origin'];
        if (!$pwd_origin) {
            fail_name('参数错误', 'pwd_origin');
        }
        $pwd_new = $data['pwd_new'];
        if (!$pwd_new) {
            fail_name('参数错误', 'pwd_new');
        }
        //判断原密码是否正确
        //查找老师
        $teacher = M('teacher')->field('uid,password,salt')->where(array(
            'uid' => $uid
        ))->find();
        if (!$teacher) {
            fail('用户不存在');
        }
        //判断密码是否正确
        if (jiami($pwd_origin . $teacher['salt']) != $teacher['password']) {
            fail('原始密码错误');
        }
        //修改密码操作
        $salt = make_salt();
        $current_time = time();
        $res = M('teacher')->where(array(
            'uid' => $uid
        ))->save(array(
            'password'    => jiami($pwd_new . $salt),
            'salt'        => $salt,
            'update_time' => $current_time,
        ));
        if (!$res) {
            fail('修改密码失败');
        } else {
            succeed(null, '修改密码成功');
        }
    }

    public function uploadImage() {
        $uploadRes = uploadFile($_FILES['img'], 3 * 1024 * 1024, array(
            'jpg',
            'gif',
            'png',
            'jpeg'
        ), 'Public/upload/teacherImgHead/');
        if ($uploadRes['uploadstatus'] == 200) {
            succeed($uploadRes, '上传成功');
        } else {
            fail($uploadRes['msg']);
        }
    }
}